package com.sigmazero13.MKDummy.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;

import com.sigmazero13.MKDummy.R;
import com.sigmazero13.MKDummy.models.MKCharacter;

public class CharacterAdapter extends BaseAdapter {
	private Context mContext;
	private List<MKCharacter> characters;
	private LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	private OnClickListener listener;
    
	
	public CharacterAdapter(Context c, MKCharacter[] characters, OnClickListener listener) {
		mContext = c;
		this.characters = new ArrayList<MKCharacter>();
		for (MKCharacter character : characters) {
			if (!character.isSpecial()) this.characters.add(character);
		}
		this.listener = listener;
	}

	@Override
	public int getCount() {
		return characters.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Button characterButton;
		
		if (convertView == null) {
			MKCharacter character = characters.get(position);
			
			characterButton = new Button(mContext);
			characterButton.setText(character.getName());
	    	characterButton.setTextSize(mContext.getResources().getDimension(R.dimen.button_text_size));
	    	characterButton.setOnClickListener(listener);
	    	characterButton.setLayoutParams(layoutParams);
	    	characterButton.setMinimumWidth(300);
	    	characterButton.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
	    	Drawable image = mContext.getResources().getDrawable(character.getFactionImageResourceId());
	    	image.setAlpha(0xff);
	    	scaleImage(image, 50);
	    	characterButton.setCompoundDrawablePadding(25);
	    	characterButton.setCompoundDrawables(image, null, null, null);
	    
		} else {
			characterButton = (Button)convertView;
			characterButton.getCompoundDrawables()[0].setAlpha(0xff);
		}
    	
		return characterButton;
	}
	
	public static void scaleImage(Drawable d, int newHeight) {
    	Rect bounds = new Rect(0,0,0,0);
    	int w = d.getIntrinsicWidth();
    	int h = d.getIntrinsicHeight();
    	float scale = ((float)newHeight)/h;
    	
    	Float newWidth = w*scale;
    	
    	bounds.right = newWidth.intValue();
    	bounds.bottom = newHeight;
    	
    	d.setBounds(bounds);
    }

}
